package com.imut.onlinebanking.dealings.service;

import com.imut.onlinebanking.dealings.entity.Account;
import com.imut.onlinebanking.dealings.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;

@Service
public class AccountsService {

    @Autowired
    private AccountMapper accountMapper;


    public Account getAccountById(Long accountId) {
        if (accountId == null) {
            throw new IllegalArgumentException("账户ID不能为空");
        }
        Account account = accountMapper.selectByAccountId(accountId);
        if (account == null) {
            throw new RuntimeException("找不到指定账户");
        }
        return account;
    }

    public List<Account> getAllAccounts() {
        return accountMapper.getAllAccounts();
    }

    @Transactional
    public boolean withdraw(Long accountId, BigDecimal amount) {
        Account account = accountMapper.selectByAccountId(accountId);
        if (account == null || account.getBalance().compareTo(amount) < 0) {
            return false;
        }

        // 使用新的withdraw方法替代updateBalance
        int rows = accountMapper.withdraw(accountId, amount);
        return rows > 0;
    }

    @Transactional
    public boolean deposit(Long accountId, BigDecimal amount) {
        // 验证金额有效性
        if (amount == null || amount.compareTo(BigDecimal.ZERO) <= 0) {
            return false;
        }

        // 查询账户是否存在
        Account account = accountMapper.selectByAccountId(accountId);

        if (account == null) {
            return false;
        }

        // 使用新的deposit方法
        int rowsAffected = accountMapper.deposit(accountId, amount);
        return rowsAffected > 0;
    }

    // 新增方法：支持通过 Account 对象查询账户
    public Account selectByAccountId(Account account) {
        return accountMapper.selectByAccountId(account.getAccountId());
    }
}
